//
//  EPUserField.m
//  UserListDemo
//
//  Created by Pill Gong on 14-1-20.
//  Copyright (c) 2014年 Pill Gong. All rights reserved.
//

#import "EPUserField.h"
#import <QuartzCore/QuartzCore.h>
#import "UIView+Addtions.h"

#define CORNER_RADIUS 10.0f
#define LABEL_MARGIN 5.0f
#define BOTTOM_MARGIN 5.0f
#define HORIZONTAL_PADDING 7.0f
#define BACKGROUND_COLOR COLOR(192, 221, 241) //[UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1.00]
#define TEXT_COLOR [UIColor blackColor]
#define TEXT_SHADOW_COLOR [UIColor whiteColor]
#define TEXT_SHADOW_OFFSET CGSizeMake(0.0f, 1.0f)
#define BORDER_COLOR COLOR(155, 192, 230)//[UIColor lightGrayColor].CGColor
#define BORDER_WIDTH 1.0f

@class EPLabel;

@protocol EPLabelDelegate <NSObject>

- (void)labelIsSelected:(EPLabel *)epLabel;

@end

@interface EPLabel : UILabel

@property (nonatomic, assign) id<EPLabelDelegate> delegate;

@end


@implementation EPLabel

- (void)addTapGesture {
    self.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelSelected:)];
    [self addGestureRecognizer:tap];
}

- (void)labelSelected:(UITapGestureRecognizer *)tap {
    if (_delegate && [_delegate respondsToSelector:@selector(labelIsSelected:)]) {
        [_delegate labelIsSelected:self];
    }
}

@end

@interface EPUserField () <EPLabelDelegate>

@property (nonatomic, assign) int selectedIndex;
@property (nonatomic, assign) CGFloat initTFHeigh;

@end

@implementation EPUserField

@synthesize view, textArray;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self addSubview:view];
        _selectedIndex = -1;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture)];
        [self addGestureRecognizer:tap];
        _initTFHeigh = MAXFLOAT;
    }
    return self;
}

- (void)tapGesture {

    [self setCursorAlpha:1];
    if (_delegate && [_delegate respondsToSelector:@selector(epuserfieldOnFoucs:)]) {
        [_delegate epuserfieldOnFoucs:self];
    }
}

- (void)setCursorAlpha:(CGFloat)alpha {
    UITextField *tf = (UITextField *)[self viewWithTag:1001];
    [tf becomeFirstResponder];
    [tf setAlpha:alpha];
}

- (BOOL)resignFirstResponder {
    UITextField *tf = (UITextField *)[self viewWithTag:1001];
    [tf resignFirstResponder];
    return [super resignFirstResponder];
}

- (void)setTags:(NSArray *)array
{
    _selectedIndex = -1;
    textArray = [[NSMutableArray alloc] initWithArray:array];
    sizeFit = CGSizeZero;
    [self display];
}

- (void)addUser:(NSString *)userName {
    _selectedIndex = -1;
    [textArray addObject:userName];
    sizeFit = CGSizeZero;
    [self display];
    [self setCursorAlpha:1];
}

- (void)setLabelBackgroundColor:(UIColor *)color
{
    lblBackgroundColor = color;
    [self display];
}

- (void)display
{
    for (UILabel *subview in [self subviews]) {
        //if (![subview isKindOfClass:[UITextField class]]) {
            [subview removeFromSuperview];
        //}
    }
    
    UIView *borderView = [[UIView alloc] initWithFrame:CGRectZero];
//    borderView.layer.borderWidth = 2.0;
//    borderView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    [self addSubview:borderView];
    
    float totalHeight = 0;
    CGRect previousFrame = CGRectZero;
    CGFloat previousHeight = [self getTextSize:@"123"].height;
    if (_initTFHeigh == MAXFLOAT) {
        _initTFHeigh = (self.height - previousHeight)*0.5;
    }
    previousFrame.origin.y = _initTFHeigh;
    previousFrame.size.height = previousHeight;
    BOOL gotPreviousFrame = NO;
    static int tagCount = 0;
    
    if (_defaultLabelText && ![@"" isEqualToString:_defaultLabelText]) {
        CGRect rect = [self addDefaultLabel];
        previousFrame = rect;
        gotPreviousFrame = YES;
        totalHeight = rect.size.height;
    }
    
    for (NSString *text in textArray) {
        tagCount++;
        CGSize textSize = [self getTextSize:text];
        EPLabel *label = nil;
        if (!gotPreviousFrame) {
            label = [[EPLabel alloc] initWithFrame:CGRectMake(0, 0, textSize.width, textSize.height)];
            totalHeight = textSize.height;
        } else {
            CGRect newRect = CGRectZero;
            if (previousFrame.origin.x + previousFrame.size.width + textSize.width + LABEL_MARGIN > self.frame.size.width) {
                newRect.origin = CGPointMake(0, previousFrame.origin.y + textSize.height + BOTTOM_MARGIN);
                totalHeight += textSize.height + BOTTOM_MARGIN;
            } else {
                newRect.origin = CGPointMake(previousFrame.origin.x + previousFrame.size.width + LABEL_MARGIN, previousFrame.origin.y);
            }
            newRect.size = textSize;
            label = [[EPLabel alloc] initWithFrame:newRect];
        }
        previousFrame = label.frame;
        gotPreviousFrame = YES;
        [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
        if (!lblBackgroundColor) {
            [label setBackgroundColor:BACKGROUND_COLOR];
        } else {
            [label setBackgroundColor:lblBackgroundColor];
        }
        label.tag = tagCount;
        [label setTextColor:TEXT_COLOR];
        [label setText:text];
        [label setTextAlignment:NSTextAlignmentCenter];
        //[label setShadowColor:TEXT_SHADOW_COLOR];
        //[label setShadowOffset:TEXT_SHADOW_OFFSET];
        [label.layer setMasksToBounds:YES];
        [label.layer setCornerRadius:CORNER_RADIUS];
        [label.layer setBorderColor:[BORDER_COLOR CGColor]];
        [label.layer setBorderWidth:BORDER_WIDTH];
        
        // TODO:
        label.delegate = self;
        [label addTapGesture];
        [self addSubview:label];
    }
    
    tagCount = 0;
    
    CGRect rect = previousFrame;
    rect.origin.x = previousFrame.origin.x + previousFrame.size.width + 2;
    rect.origin.y = previousFrame.origin.y + 1;
    rect.size.width = 5;
    rect.size.height = previousFrame.size.height;
    UITextField *tf = [[UITextField alloc] initWithFrame:rect];
    //tf.backgroundColor = [UIColor redColor];
    tf.tag = 1001;
    tf.text = @" ";
    tf.delegate = self;
    //[tf becomeFirstResponder];
    [self addSubview:tf];
    sizeFit = CGSizeMake(self.frame.size.width, totalHeight + 1.0f);
    
    borderView.frame = CGRectMake(-5, -5, sizeFit.width+10, (sizeFit.height >= 23 ? sizeFit.height : 23)+10);
}

- (CGSize)getTextSize:(NSString *)text {
    CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:CGSizeMake(self.frame.size.width, 1500) lineBreakMode:NSLineBreakByWordWrapping];
    textSize.width += HORIZONTAL_PADDING*2;
    textSize.height += VERTICAL_PADDING*2;
    return textSize;
}

- (CGRect)addDefaultLabel {
    CGSize textSize = [self getTextSize:_defaultLabelText];
    UILabel *defaultLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, textSize.width-HORIZONTAL_PADDING*2, textSize.height)];
    defaultLabel.backgroundColor = [UIColor clearColor];
    defaultLabel.text = _defaultLabelText;
    defaultLabel.font = [UIFont systemFontOfSize:FONT_SIZE];
//    defaultLabel.textColor = [UIColor grayColor];
    [self addSubview:defaultLabel];
    return defaultLabel.frame;
}

- (CGSize)fittedSize
{
    return sizeFit;
}

- (CGFloat)getUserFieldHeight {
    return sizeFit.height;
}

- (void)updateLabelsColor:(int)index {
    for (int i=1; i<=textArray.count; i++) {
        [self setLabelColor:i highlight:(i == index)];
    }
}

- (void)selectLabelAtIndex:(int)index {
    if (!index) {
        return;
    }
    _selectedIndex = index;
    [self setLabelColor:index highlight:YES];
    [self setCursorAlpha:0];
    if (_delegate && [_delegate respondsToSelector:@selector(epuserfield:selectedIndex:)]) {
        [_delegate epuserfield:self selectedIndex:index-1];
    }
}

- (void)setLabelColor:(int)index highlight:(BOOL)anmited {
    UILabel *label = (UILabel *)[self viewWithTag:index];
    if (anmited) {
        label.backgroundColor = UIColorFromRGB(0x007AFF);
        label.textColor = [UIColor whiteColor];
    } else {
        if (!lblBackgroundColor) {
            [label setBackgroundColor:BACKGROUND_COLOR];
        } else {
            [label setBackgroundColor:lblBackgroundColor];
        }
        label.textColor = [UIColor blackColor];
    }
}

- (void)deleteLabelAtIndex:(int)index {
    [textArray removeObjectAtIndex:index-1];
    [self display];
    [self setCursorAlpha:1];
    _selectedIndex = -1;
    if (_delegate && [_delegate respondsToSelector:@selector(epuserfield:removedIndex:)]) {
        [_delegate epuserfield:self removedIndex:index-1];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    if ([newString isEqualToString:@""] &&
        [string isEqualToString:@""] &&
        range.location == 0 &&
        range.length == 1)
    {
        if (_selectedIndex == -1) {
            [self selectLabelAtIndex:textArray.count];
        } else {
            if (_deleteActionFail == NO) {
                [self deleteLabelAtIndex:_selectedIndex];
            }
        }
        return NO;
    }
    
    return NO;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (_delegate && [_delegate respondsToSelector:@selector(epuserfieldOnBlur:)]) {
        [_delegate epuserfieldOnBlur:self];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - EPLabelDelegate

- (void)labelIsSelected:(EPLabel *)epLabel {
    [self setCursorAlpha:0];
    _selectedIndex = epLabel.tag;
    [self updateLabelsColor:epLabel.tag];
}


@end